#include "user_flash.h"

/**
 * @brief Flash写入函数（擦除+验证+写入）
 * @param addr 写入地址
 * @param message 要写入的字符串
 * @return int 返回1表示成功，0表示失败
 */
int flash_write(uint32_t addr, const char *message)
{

    uint8_t read_buffer[SPI_FLASH_PAGE_SIZE];
    uint8_t write_buffer[SPI_FLASH_PAGE_SIZE];
    
    // 擦除扇区
    //user_printf(&huart1, "Erasing sector at address 0x%lX...\r\n", addr);
    spi_flash_sector_erase(addr);
    //user_printf(&huart1, "Sector erased.\r\n");
    
    // 验证擦除：读取一页数据检查是否全为0xFF
    spi_flash_buffer_read(read_buffer, addr, SPI_FLASH_PAGE_SIZE);
    int erased_check_ok = 1;
    for (int i = 0; i < SPI_FLASH_PAGE_SIZE; i++)
    {
        if (read_buffer[i] != 0xFF)
        {
            erased_check_ok = 0;
            break;
        }
    }
    if (erased_check_ok)
    {
        //user_printf(&huart1, "Erase check PASSED. Sector is all 0xFF.\r\n");
    }
    else
    {
        //user_printf(&huart1, "Erase check FAILED.\r\n");
        return 0; // 擦除验证失败
    }
    
    // 准备要写入的数据
    uint16_t data_len = strlen(message);
    if (data_len >= SPI_FLASH_PAGE_SIZE)
    {
        data_len = SPI_FLASH_PAGE_SIZE - 1; // 确保不超过页大小
    }
    memset(write_buffer, 0, SPI_FLASH_PAGE_SIZE);
    memcpy(write_buffer, message, data_len);
    write_buffer[data_len] = '\0'; // 确保字符串结束符
    
    //user_printf(&huart1, "Writing data to address 0x%lX: \"%s\"\r\n", addr, write_buffer);
    
    // 写入数据
    spi_flash_buffer_write(write_buffer, addr, SPI_FLASH_PAGE_SIZE); // 写入整个页面
    //user_printf(&huart1, "Data written.\r\n");
    
    return 1; // 成功
}
